package cn.itcast.web;

import cn.itcast.mapper.adminMapper;
import cn.itcast.mapper.horsemanMapper;
import cn.itcast.mapper.temporaryOrderMapper;
import cn.itcast.mapper.userMapper;
import cn.itcast.pojo.*;
import cn.itcast.service.impl.orderServiceImpl;
import cn.itcast.util.*;
import cn.message.service.impl.MessageOrderServiceImpl;
import cn.web.web_module.service.impl.AutomaticSendImpl;
import cn.web.web_module.util.IconPath;
import cn.wx.MyConfig;
import cn.wx.UserWxPayMyConfig;
import cn.wx.WXPay;
import cn.wx.WXPayUtil;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;


import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.Date;

/**
 * @Description: ${订单控制类}
 * @return ${return_type}
 * @throws
 * @author 欧阳辉
 * @date 2020/3/16 16:57
 */

@Slf4j
@RestController
@RequestMapping(value="/wxshop/user",produces="text/html;charset=UTF-8")
public class orderController {

    //    @Autowired
    @Autowired
    private StringRedisTemplate template;
    // @Autowired
    // private DataSource dataSource;


    @Resource
    cn.itcast.mapper.rechargeMapper rechargeMapper;

    @Resource
    cn.itcast.mapper.accountMapper accountMapper;

    @Resource
    orderServiceImpl orderService;
    @Resource
    temporaryOrderMapper temporaryOrderMapper;
    @Resource
    OutputStringController osc;

    @Resource
    private MessageOrderServiceImpl messageOrderService;

    @Resource
    private AutomaticSendImpl automaticSend;
    @Resource
    cn.itcast.mapper.orderMapper orderMapper;

    @Resource
    cn.itcast.mapper.orderItemMapper orderItemMapper;

    @Resource
    private orderServiceImpl orderServiceimpl;

    @Resource
    cn.itcast.mapper.classsifyMapper classsifyMapper;

    @Resource
    cn.itcast.mapper.commissionMapper commissionMapper;

    @Resource
    private cn.itcast.mapper.userMapper userMapper;

    @Resource
    private adminMapper adminMapper;

    @Resource
    private cn.itcast.mapper.horsemanMapper horsemanMapper;

    private Map<String,Object> result = new HashMap<>();

    /**
     *
     * @Description:
     * 查询首页最新回收订单滚动
     * @auther: 欧阳
     * @date: 14:51 2021/10/28
     * @param: [map]
     * @return: map
     *
     */
    @ApiOperation("首页最新回收订单滚动")
    @PostMapping(value = "/toptenorder",produces = "text/html;charset=utf-8")
    public String toptenorder(){
        log.debug("查询首页最新回收订单滚动");
        //返回结果
        List<order> toporderlist = orderService.toporderimpl();
        String json= JSON.toJSONString(toporderlist);
        return json;
    }





    /**
     *功能：判断用户是否是提现管理员或超级管理员
     * @author 欧阳辉
     * @date 2021-05-29
     * @param map
     * @return java.lang.String
     */
    @PostMapping("/isWithdrawAdmin")
    public String isWithdrawAdmin(@RequestBody Map<String,String> map){
        log.debug("判断用户是否是提现管理员或超级管理员");
        String openId = map.get("openId");
        user user = userMapper.selectByPrimaryKey(openId);

        admin admin = adminMapper.selectPhone(user.getUserPhone());

        try {
            List<Integer> roles = adminMapper.getRoleIdsByAdminId(admin.getAdminId());
            for (Integer roleId :roles){
                if(roleId==2 || roleId==6){
                    log.debug("判断用户是否是提现管理员或超级管理员");
                    return osc.resultSuccess("yes","");
                }
            }
        }catch (Exception e){
            log.debug("判断用户是否是提现管理员或超级管理员");
            return osc.resultFailure("no", "");
        }


        log.debug("获判断用户是否是管理员失败");
        return osc.resultFailure("no", "");


    }

    /**
     *功能：判断用户是否是管理员
     * @author 欧阳辉
     * @date 2021-05-29
      * @param map
     * @return java.lang.String
     */
    @PostMapping("/isAdmin")
    public String isAdmin(@RequestBody Map<String,String> map){
        log.debug("判断用户是否是管理员");
        String openId = map.get("openId");
        user user = userMapper.selectByPrimaryKey(openId);

        admin admin = adminMapper.selectPhone(user.getUserPhone());

        try {
            List<Integer> roles = adminMapper.getRoleIdsByAdminId(admin.getAdminId());
            for (Integer roleId :roles){
                if(roleId==2 || roleId==6 || roleId == 24){
                    log.debug("判断用户是否是管理员成功");
                    return osc.resultSuccess("yes","");
                }
            }
        }catch (Exception e){
            log.debug("获判断用户是否是管理员失败");
            return osc.resultFailure("no", "");
        }


        log.debug("获判断用户是否是管理员失败");
        return osc.resultFailure("no", "");


    }



    /**
     *
     * @Description:
     * 生成订单前的上传图片
     * @auther: 欧阳辉
     * @date: 8:12 2020/3/17
     * @param: [request]
     * @return: java.lang.String
     *
     */
    @PostMapping("uploadOrder")
    public String uploadOrder(HttpServletRequest request) throws IllegalStateException, IOException {
        //返回结果
        String results="";

        //获取订单编号
        String number = request.getParameter("number");


        //将当前上下文初始化给  CommonsMutipartResolver （多部分解析器）
        CommonsMultipartResolver multipartResolver=new CommonsMultipartResolver(
                request.getSession().getServletContext());
        //检查form中是否有enctype="multipart/form-data"
        if(multipartResolver.isMultipart(request))
        {
            //将request变成多部分request
            MultipartHttpServletRequest multiRequest=(MultipartHttpServletRequest)request;
            //获取multiRequest 中所有的文件名
            Iterator iter=multiRequest.getFileNames();

            while(iter.hasNext())
            {
                //一次遍历所有文件
                MultipartFile file=multiRequest.getFile(iter.next().toString());
                if(file!=null)
                {
                    SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMddHHmmss");
                    String newDate=sdf.format(new Date());
                    //服务器存储图片地址
                    //服务器地址：“/usr/tomcat/images/dhn/icon/orderItem/”
                    //String filePath= "D:/Desktop/icon/order/"+newDate+"/"+file.getOriginalFilename();
//                    String filePath="/usr/tomcat/images/dhn/icon/order/"+newDate+"/"+file.getOriginalFilename();    //松注释
//                    File files=new File("/usr/tomcat/images/dhn/icon/order/"+newDate);  //松注释
                    String filePath= IconPath.ICONPATH +"icon/order/"+newDate+"/"+file.getOriginalFilename();    //松注释
                    File files=new File(IconPath.ICONPATH +"icon/order/"+newDate);  //松注释
                    //File files=new File("D:/Desktop/icon/order/"+newDate);
                    if(!files.exists()){//如果文件夹不存在
                        files.mkdir();//创建文件夹
                    }
                    //数据库存放访问地址
                    String path="https://www.dhnep.cn:8181/dhn/icon/order/"+newDate+"/"+file.getOriginalFilename();
                    boolean isadd = orderService.addImgPath(path,number);
                    if(isadd) {
                        //上传图片至服务器
                        file.transferTo(new File(filePath));
                        results = osc.success("yes");
                        log.debug("上传成功");
                    }else {
                        results = osc.failure("no");
                        log.debug("上传失败");
                    }

                }

            }

        }


        return results;
    }


    /**
     *
     * @Description:
     * 用户生成订单
     * @auther: 欧阳辉
     * @date: 8:12 2020/3/17
     * @param: [request]
     * @return: java.lang.String
     *
     */
    @PostMapping("addOrder")
    public String addOrder(@RequestBody Map<String,String> map) {
        //返回结果
        String results="";
        order order = new order();
        log.debug("添加订单开始");
        order.setOrderState("待派单");
        String orderNumber = getOrderIdByTime();
        order.setOrderNumber(orderNumber);
        order.setOrderVisitTime(map.get("visitTime"));
        order.setOrderTime(new Date());
        order.setLat(map.get("lat"));
        order.setLon(map.get("lat"));
        order.setLat(map.get("addressLat"));
        order.setLon(map.get("addressLon"));
        order.setUserName(map.get("userName"));
        order.setUserArea(map.get("userarea"));
        order.setCounty(map.get("county"));
        order.setUserPhone(map.get("userPhone"));
        order.setOrderExplain(map.get("explain"));
        order.setPayProductType(map.get("productType"));
        order.setPayForecastWeight(map.get("forecastWeight"));
        order.setOpenId(map.get("openId"));
        order.setOrderform("1");

        //生成订单，推送消息给管理员
        boolean isadd = orderService.addOrder(order,map.get("productId"));
        if(isadd) {
            Double lat; //纬度
            Double lon; //经度
            if (Strings.isBlank(map.get("lat"))||Strings.isBlank(map.get("lon"))||"0".equals(map.get("lon"))||"0".equals(map.get("lat"))){
                Map<String, Double> userarea = orderServiceimpl.getLngAndLat(map.get("userarea"));
                lat=userarea.get("lat");
                lon=userarea.get("lng");
            }else {
                lat=Double.parseDouble(map.get("lat"));
                lon=Double.parseDouble(map.get("lon"));
            }
            Map<String,Double> latAndLon = new HashMap<>();
            latAndLon.put("userLat",lat);
            latAndLon.put("userLon",lon);
            user user = userMapper.selectFindOneUser(map.get("openId"));
            if (StringUtils.isNotBlank(user.getBindHorseman())){
                List<horseman> userBindHorsemen = horsemanMapper.selectHorsemanphone(user.getBindHorseman());
                if (!userBindHorsemen.isEmpty()||userBindHorsemen.size()>0){
                    messageOrderService.sendOrder(order.getId(),userBindHorsemen.get(0).getOpenId(),userBindHorsemen.get(0).getHorsemanName());
                    log.debug("上传成功");
                    results = osc.resultSuccess("yes",orderNumber);
                    return results;
                    // 如果用户有绑定的骑手 则派单给相应骑手
                }
            }
            // 如果是合作骑手的话只给绑定了的单给合作骑手 返回map存储的是离用户最近的骑手和距离
            Map<String, Object> approachingHorseman = automaticSend.getApproachingHorseman(latAndLon);
            List<horseman> minDistanceHorsemen = (List) approachingHorseman.get("minDistanceHorsemen");
            messageOrderService.sendOrder(order.getId(),minDistanceHorsemen.get(0).getOpenId(),minDistanceHorsemen.get(0).getHorsemanName());
            // 根据用户经纬度获取到离最近的骑手,派单给骑手

            log.debug("上传成功");
            results = osc.resultSuccess("yes",orderNumber);
        }else {
            results = osc.failure("no");
            log.debug("上传失败");
        }

        return results;
    }

    private boolean ifHorsemanOrderSize() {
        List<horseman> horsemen = horsemanMapper.selectHorsemanOrderNumber();
        horsemanMapper.ifIsOpen();
        return true;
    }


    /**
     *
     * @Description:
     * 随机生成订单号
     * @auther: 欧阳辉
     * @date: 8:23 2020/3/17
     * @param: []
     * @return: java.lang.String
     *
     */
    public String getOrderIdByTime() {
        SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMddHHmmss");
        String newDate=sdf.format(new Date());
        String result="";
        Random random=new Random();
        for(int i=0;i<3;i++){
            result+=random.nextInt(10);
        }
        return newDate+result;
    }



    /**
     *
     * @Description:
     * 获取用户各状态订单
     * @auther: 欧阳辉
     * @date: 11:33 2020/3/17
     * @param: [map]
     * @return: java.lang.String
     *
     */
    @PostMapping("/findOrder")
    public String findOrder(@RequestBody Map<String,String> map){
        log.debug("获取用户各状态订单！！！");
        String orderStatus = map.get("orderStatus");
        String openId = map.get("openId");
        //返回结果
        String results ="";
        List<order> orders = orderService.findOrder(orderStatus,openId);
        if (orderStatus.equals("进行中")){
            for (order order : orders) {
                String horsemanAccount = order.getHorsemanAccount();
                List<horseman> horsemen = horsemanMapper.selectHorsemanOpenId(horsemanAccount);
                order.setExploitName(horsemen.get(0).getHorsemanPhone());
            }
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:MM:SS");
        for (order order : orders) {
            if(StringUtils.isNotBlank(ObjectUtils.toString(order.getPayTime()))){
                order.setPayTimeString(sdf.format(order.getPayTime()));
            }
        }
        if (orders.isEmpty()) {
            results = osc.resultFailure("no", "");
            log.debug("获取用户各状态订单失败");
        } else {
            results = osc.resultSuccess("yes", orders);
            log.debug("获取用户各状态订单成功");
        }
        return results;

    }

    /**
     * 功能描述: <br>
     * 〈查看订单详情〉
     * @Author: lyy
     * @Date: 2020/7/4 10:12
     * @Param: [map]
     * @Return: java.lang.String
     */
    @RequestMapping(value = "/userOrder")
    public String userOrder(@RequestBody Map<String,String> map){
        log.debug("查看订单详情页面！！！");
        String orderStatus = map.get("orderStatus");
        String openId = map.get("openId");
        //返回结果
        String results ="";
        List<order> orders = orderService.findUserOrder(orderStatus,openId);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:MM:SS");
        for (order order : orders) {
            if(StringUtils.isNotBlank(ObjectUtils.toString(order.getPayTime()))){
                String format = sdf.format(order.getPayTime());
                order.setOrderVisitTime(format);
            }
        }
        if (orders.isEmpty()) {
            results = osc.resultFailure("no", "");
            log.debug("获取用户订单详情失败");
        } else {
            results = osc.resultSuccess("yes", orders);
            log.debug("获取用户订单详情成功");
        }
        return results;
    }



    /**
     *
     * @Description:
     * 获取某一状态订单
     * @auther: 欧阳辉
     * @date: 11:33 2020/3/17
     * @param: [map]
     * @return: java.lang.String
     *
     */
    @PostMapping("/findStatusOrder")
    public String findStatusOrder(@RequestBody Map<String,String> map){
        log.debug("获取用户各状态订单！！！");
        String orderStatus = map.get("orderStatus");
        //返回结果
        String results ="";
        List<order> orders = orderService.findStatusOrder(orderStatus);
        if (orders.isEmpty()) {
            results = osc.resultFailure("no", "");
            log.debug("获取某一状态订单失败");
        } else {
            results = osc.resultSuccess("yes", orders);
            log.debug("获取某一状态订单成功");
        }
        return results;

    }

    /**
     *
     * @Description:
     * 获取一二级分销订单
     * @auther: 欧阳辉
     * @date: 11:33 2020/3/17
     * @param: [map]
     * @return: java.lang.String
     *
     */
    @PostMapping("/findDistributionOrder")
    public String findDistributionOrder(@RequestBody Map<String,String> map){
        log.debug("获取一二级分销订单！！！");
        String openId = map.get("openId");
        //返回结果
        String results ="";
        Map<String,List<order>> orders = orderService.findDistributionOrder(openId);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:MM:SS");
        for (order order : orders.get("one")) {
            if(StringUtils.isNotBlank(ObjectUtils.toString(order.getPayTime()))){
                order.setPayTimeString(sdf.format(order.getPayTime()));
                BigDecimal b = new BigDecimal(order.getPayOrderMoney()*0.02);
                order.setPayOrderMoney(b.setScale(2, BigDecimal.ROUND_DOWN).doubleValue());
            }
        }
        for (order order : orders.get("two")) {
            if(StringUtils.isNotBlank(ObjectUtils.toString(order.getPayTime()))){
                order.setPayTimeString(sdf.format(order.getPayTime()));
                BigDecimal b = new BigDecimal(order.getPayOrderMoney()*0.01);
                order.setPayOrderMoney(b.setScale(2, BigDecimal.ROUND_DOWN).doubleValue());
            }
        }
        if (orders.isEmpty()) {
            results = osc.resultFailure("no", "");
            log.debug("获取一二级分销订单失败");
        } else {
            results = osc.resultSuccess("yes", orders);
            log.debug("获取一二级分销订单成功");
        }
        return results;

    }

    /**
     *
     * @Description:
     * 删除订单
     * @auther: 欧阳辉
     * @date: 14:51 2020/3/17
     * @param: [map]
     * @return: java.lang.String
     *
     */
    @PostMapping("/delectOrder")
    public String delectOrder(@RequestBody Map<String,String> map){
        log.debug("删除订单");
        //获取地址信息
        Integer orderId =Integer.parseInt(map.get("orderId"));
        String explain =map.get("explain");
        //返回结果
        String results = "";
        boolean isdelect = orderService.delectOrder(orderId,explain);
        if(isdelect){
            results = osc.success("yes");

            log.debug("删除订单成功");
        }else{
            results = osc.failure("no");
            log.debug("删除订单失败");
        }

        return results;
    }

    public void pust(){

    }

//    /**
//     * @Description: ${4,确认收货(未收货页面删除，待评价页面增加)}
//     * @return ${return_type}
//     * @throws
//     * @author 徐威
//     * @date 2019/6/18 8:53
//     */
//    @PostMapping("/confirmReception")
//    public String confirmReception(@RequestBody Map<String,String> map){
//
//        order  order=new order();
//        order.setOrderId(Integer.valueOf(map.get("orderId")));
//        order.setOrderStatus(Integer.valueOf(map.get("orderStatus")));
////        Integer orderId =Integer.parseInt(map.get("orderId"));
////        order.setOrderStatus(2);
//        //返回结果
//        String results = "";
//        boolean isupdate = orderService.updateOrder(order);
//        if(isupdate){
//            results = osc.success("yes");
//            log.debug("修改成功");
//        }else{
//            results = osc.failure("no");
//            log.debug("修改失败");
//        }
//
//        return results;
//    }


    /**
     * @Description: ${5,评价(待评价页面删除)}
     * @return ${return_type}
     * @throws
     * @author 徐威
     * @date 2019/6/18 8:55
     */
    @PostMapping("/evaluate")
    public String evaluate(@RequestBody Map<String,String> map){
        Integer orderId =Integer.parseInt(map.get("orderId"));
//        boolean isdelect = orderService.delectOrder(orderId);
//        //返回结果
        String results = "";
//        if(isdelect){
//            results = osc.success("yes");
//            log.debug("删除评价订单成功");
//        }else{
//            results = osc.failure("no");
//            log.debug("删除评价订单失败");
//        }
//
        return results;
    }






    /**
     *
     * @Description:
     * 大黄牛临时下单连接
     * @auther: 欧阳辉
     * @date: 14:51 2020/3/17
     * @param: [map]
     * @return: java.lang.String
     *
     */
    @PostMapping("/productOrder")
    public String productOrder(HttpServletRequest request, @RequestBody Map<String,String> map){
        log.debug("删除订单");
        //获取地址信息
        String recycle =map.get("recycle");
        String exploit =map.get("exploit");
        String client =map.get("client");
        String tel =map.get("tel");
        String area =map.get("area");
        String address =map.get("address");
        String date =map.get("date");
        //String da = cn.itcast.util.Date.transferDateFormat(date).toString();

        temporaryOrder temporaryOrder = new temporaryOrder();
        temporaryOrder.setRecycle(recycle);
        temporaryOrder.setExploit(exploit);
        temporaryOrder.setClient(client);
        temporaryOrder.setTel(tel);
        temporaryOrder.setArea(area);
        temporaryOrder.setAddress(address);
        temporaryOrder.setDate(date);
        //返回结果
        String results = "";
        Integer id = orderService.productOrder(temporaryOrder);

        List<String> receivers = new ArrayList<>();
        receivers.add("634272623@qq.com");
        receivers.add("fdf@dhnep.com");
        receivers.add("xiaoyuan@dhnep.com");
        receivers.add("zxq@dhnep.com");
        receivers.add("hhm@dhnep.com");
        receivers.add("hzh@dhnep.com");

        //发送邮箱
        SendEmail sendEmail = new SendEmail();
        //返回
        int code = sendEmail.sendMail(receivers,temporaryOrder);

        if(id!=1){
            results = osc.resultSuccess("yes",id);
            log.debug("删除订单成功");
        }else{
            results = osc.failure("no");
            log.debug("删除订单失败");
        }

        return results;
    }

    /**
     *
     * @Description:
     * 大黄牛临时下单连接
     * @auther: 欧阳辉
     * @date: 14:51 2020/3/17
     * @param: [map]
     * @return: java.lang.String
     *
     */
    @PostMapping("/productOrderItem")
    public String productOrderItem(@RequestBody Map<String,String> map){
        Integer orderId = Integer.valueOf(map.get("orderId"));
        double roughWeight = Double.parseDouble(map.get("roughWeight"));
        double tare = Double.parseDouble(map.get("tare"));
        double suttle = Double.parseDouble(map.get("suttle"));
        double unitPrice = Double.parseDouble(map.get("unitPrice"));
        double price = Double.parseDouble(map.get("price"));
        double transport = Double.parseDouble(map.get("transport"));
        double develop = Double.parseDouble(map.get("develop"));
        String expl = map.get("expl");
        String fileList =map.get("fileList");
        String type =map.get("type");
        String typeInfo =map.get("typeInfo");

        temporaryOrderItem temporaryOrderItem = new temporaryOrderItem();
        temporaryOrderItem.setRoughweight(roughWeight);
        temporaryOrderItem.setTare(tare);
        temporaryOrderItem.setSuttle(suttle);
        temporaryOrderItem.setUnitprice(unitPrice);
        temporaryOrderItem.setPrice(price);
        temporaryOrderItem.setTransport(transport);
        temporaryOrderItem.setDevelop(develop);
        temporaryOrderItem.setFilelist(fileList);
        temporaryOrderItem.setType(type);
        temporaryOrderItem.setExpl(expl);
        temporaryOrderItem.setTypeinfo(typeInfo);
        temporaryOrderItem.setOrderId(orderId);
        //返回结果
        String results = "";
        Integer id = orderService.productOrderItem(temporaryOrderItem);
        if(id!=1){
            results = osc.resultSuccess("yes",id);
            log.debug("删除订单成功");
        }else{
            results = osc.failure("no");
            log.debug("删除订单失败");
        }

        return results;
    }




    /**
     *
     * @Description:
     * 大黄牛临时下单连接上传图片
     * @auther: 欧阳辉
     * @date: 8:12 2020/3/17
     * @param: [request]
     * @return: java.lang.String
     *
     */
    @PostMapping("productuploadOrder")
    public String productuploadOrder(HttpServletRequest request) throws IllegalStateException, IOException {
        //返回结果
        String results="";

        //获取订单编号
        Integer orderItemId = Integer.valueOf(request.getParameter("orderItemId"));


        //将当前上下文初始化给  CommonsMutipartResolver （多部分解析器）
        CommonsMultipartResolver multipartResolver=new CommonsMultipartResolver(
                request.getSession().getServletContext());
        //检查form中是否有enctype="multipart/form-data"
        if(multipartResolver.isMultipart(request))
        {
            //将request变成多部分request
            MultipartHttpServletRequest multiRequest=(MultipartHttpServletRequest)request;
            //获取multiRequest 中所有的文件名
            Iterator iter=multiRequest.getFileNames();

            while(iter.hasNext())
            {
                //一次遍历所有文件
                MultipartFile file=multiRequest.getFile(iter.next().toString());
                if(file!=null)
                {
                    SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMddHHmmss");
                    String newDate=sdf.format(new Date());
                    //服务器存储图片地址
                    //服务器地址：“/usr/tomcat/images/dhn/icon/orderItem/”
                    //String filePath= "D:/Desktop/icon/order/"+newDate+"/"+file.getOriginalFilename();
//                    String filePath="/usr/tomcat/images/dhn/icon/order/"+newDate+"/"+file.getOriginalFilename();    //松注释
//                    File files=new File("/usr/tomcat/images/dhn/icon/order/"+newDate);  //松注释

                    String filePath=IconPath.ICONPATH +"icon/order/"+newDate+"/"+file.getOriginalFilename();
                    File files=new File(IconPath.ICONPATH +"icon/order/"+newDate);
                    //File files=new File("D:/Desktop/icon/order/"+newDate);
                    if(!files.exists()){//如果文件夹不存在
                        files.mkdir();//创建文件夹
                    }
                    //数据库存放访问地址
                    String path="https://www.dhnep.cn:8181/dhn/icon/order/"+newDate+"/"+file.getOriginalFilename();
                    boolean isadd = orderService.productuploadOrder(path,orderItemId);
                    if(isadd) {
                        //上传图片至服务器
                        file.transferTo(new File(filePath));
                        results = osc.success("yes");
                        log.debug("上传成功");
                    }else {
                        results = osc.failure("no");
                        log.debug("上传失败");
                    }

                }

            }

        }


        return results;
    }



    /**
     *
     * @Description:
     * 大黄牛临时下单连接上传图片
     * @auther: 欧阳辉
     * @date: 8:12 2020/3/17
     * @param: [request]
     * @return: java.lang.String
     *
     */
    @PostMapping("accessoryuploadOrder")
    public String accessoryuploadOrder(HttpServletRequest request) throws IllegalStateException, IOException {
        //返回结果
        String results="";

        //获取订单编号
        Integer orderItemId = Integer.valueOf(request.getParameter("orderItemId"));


        //将当前上下文初始化给  CommonsMutipartResolver （多部分解析器）
        CommonsMultipartResolver multipartResolver=new CommonsMultipartResolver(
                request.getSession().getServletContext());
        //检查form中是否有enctype="multipart/form-data"
        if(multipartResolver.isMultipart(request))
        {
            //将request变成多部分request
            MultipartHttpServletRequest multiRequest=(MultipartHttpServletRequest)request;
            //获取multiRequest 中所有的文件名
            Iterator iter=multiRequest.getFileNames();

            while(iter.hasNext())
            {
                //一次遍历所有文件
                MultipartFile file=multiRequest.getFile(iter.next().toString());
                if(file!=null)
                {
                    SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMddHHmmss");
                    String newDate=sdf.format(new Date());
                    //服务器存储图片地址
                    //服务器地址：“/usr/tomcat/images/dhn/icon/orderItem/”
                    //String filePath= "D:/Desktop/icon/order/"+newDate+"/"+file.getOriginalFilename();
//                    String filePath="/usr/tomcat/images/dhn/icon/order/"+newDate+"/"+file.getOriginalFilename();    //松注释
//                    File files=new File("/usr/tomcat/images/dhn/icon/order/"+newDate);      //松注释


                    String filePath=IconPath.ICONPATH +"icon/order/"+newDate+"/"+file.getOriginalFilename();
                    File files=new File(IconPath.ICONPATH +"icon/order/"+newDate);
                    //File files=new File("D:/Desktop/icon/order/"+newDate);
                    if(!files.exists()){//如果文件夹不存在
                        files.mkdir();//创建文件夹
                    }
                    //数据库存放访问地址
                    String path="https://www.dhnep.cn:8181/dhn/icon/order/"+newDate+"/"+file.getOriginalFilename();
                    boolean isadd = orderService.accessoryuploadOrder(path,orderItemId);
                    if(isadd) {
                        //上传图片至服务器
                        file.transferTo(new File(filePath));
                        results = osc.success("yes");
                        log.debug("上传成功");
                    }else {
                        results = osc.failure("no");
                        log.debug("上传失败");
                    }

                }

            }

        }


        return results;
    }



    /**
     *
     * @Description:
     * 大黄牛临时下单连接查询所有订单
     * @auther: 欧阳辉
     * @date: 11:33 2020/3/17
     * @param: [map]
     * @return: java.lang.String
     *
     */
    @PostMapping("/temporaryfindAllOrder")
    public String temporaryfindAllOrder(@RequestBody Map<String,String> map){
        log.debug("大黄牛临时下单连接查询所有订单！！！");
        Integer page = Integer.valueOf(map.get("page"));
        Integer limit = Integer.valueOf(map.get("limit"));
        String select = map.get("select");
        String value = map.get("value");
        //返回结果
        String results ="";
        List<temporaryOrder> orders = orderService.temporaryfindAllOrder(page,limit,select,value);
        List<temporaryOrder> temporaryOrders = temporaryOrderMapper.selectByExample(new temporaryOrderExample());
        if (orders.isEmpty()) {
            results = osc.resultFailure("no", "");
            log.debug("大黄牛临时下单连接查询所有订单失败");
        } else {
            results = osc.resultSuccess("yes", orders,temporaryOrders.size());
            log.debug("大黄牛临时下单连接查询所有订单成功");
        }
        return results;

    }

    /**
     *
     * @Description:
     * 大黄牛临时下单连接查询订单详细
     * @auther: 欧阳辉
     * @date: 11:33 2020/3/17
     * @param: [map]
     * @return: java.lang.String
     *
     */
    @PostMapping("/temporaryfindOrderItem")
    public String temporaryfindOrderItem(@RequestBody Map<String,String> map){
        log.debug("大黄牛临时下单连接查询所有订单！！！");
        Integer orderId = Integer.valueOf(map.get("orderId"));
        //返回结果
        String results ="";
        List<temporaryOrderItem> orders = orderService.temporaryfindOrderItem(orderId);
        if (orders.isEmpty()) {
            results = osc.resultFailure("no", "");
            log.debug("大黄牛临时下单连接查询所有订单失败");
        } else {
            results = osc.resultSuccess("yes", orders);
            log.debug("大黄牛临时下单连接查询所有订单成功");
        }
        return results;

    }
    /**
     *
     * @Description:
     * 查询用户是够已经有未完成的订单
     * @auther: 欧阳辉
     * @date: 11:33 2020/3/17
     * @param: [map]
     * @return: java.lang.String
     *
     */
    @PostMapping("/findUserUnfinishOrder")
    public String findUserUnfinishOrder(@RequestBody Map<String,String> map){
        log.debug("查询用户是够已经有未完成的订单！！！");
        String openId = map.get("openId");
        //返回结果
        String results ="";
        Integer orderId = orderService.findUserUnfinishOrder(openId);
        if (orderId==0) {
            results = osc.resultFailure("no", "");
            log.debug("查询用户是够已经有未完成的订单失败");
        } else {
            results = osc.resultSuccess("yes", orderId);
            log.debug("查询用户是够已经有未完成的订单成功");
        }
        return results;

    }

    @RequestMapping(value = "/orderPay")
    public String orderPay(@RequestBody Map<String,String> map){
        log.debug("用户支付订单！！！");
        String results ="";
        Integer orderId = Integer.parseInt(map.get("orderId")); //订单id
        String openId = map.get("openId");  //用户的
        double price = Double.parseDouble(map.get("totalFee"));
        String payType = map.get("payType");    //支付方式 （环保金/微信）
        accountExample userEx = new accountExample();
        accountExample.Criteria userCriteria = userEx.createCriteria();
        userCriteria.andOpenIdEqualTo(openId);
        userCriteria.andAccountTypeidEqualTo(2);
        List<account> accounts = accountMapper.selectByExample(userEx);    //用户数据
        order order = orderMapper.selectByPrimaryKey(orderId);  //订单数据
        accountExample aEx = new accountExample();
        accountExample.Criteria criteria = aEx.createCriteria();
        criteria.andOpenIdEqualTo(order.getHorsemanAccount());  //骑手openId
        criteria.andAccountTypeidEqualTo(1);
        List<account> criteriaList = accountMapper.selectByExample(aEx);
        if(criteriaList!=null&&criteriaList.size()>0 || accounts!=null&&accounts.size()>0){
            if(payType!=null&&payType.equals("环保金")){   //环保金
                double money = DoubleUtils.sub(accounts.get(0).getAccountMoneyBalance(),price);
                if(money>=0||money==0){ //环保金足够支付
                    //修改用户余额    添加骑手用户余额
                    accounts.get(0).setAccountMoneyBalance(money);
                    int updateUser = accountMapper.updateByPrimaryKeySelective(accounts.get(0));
//                    criteriaList.get(0).setAccountMoneyBalance(DoubleUtils.add(criteriaList.get(0).getAccountMoneyBalance(), price));
//                    int updateHores = accountMapper.updateByPrimaryKeySelective(criteriaList.get(0));
                    boolean flag = commission(map.get("orderId"),price,order.getHorsemanAccount());
                    if(updateUser!=0||updateUser>0 && flag==true) {
                        order.setPayOrderMoney(price);
                        order.setOrderState("已完成");
                        orderMapper.updateByPrimaryKeySelective(order);
                        orderItem(map.get("orderId"));
                        log.info("余额支付成功！！！");
                        results = osc.success("余额支付成功");
                    }else{
                        log.info("余额支付失败！！！");
                        results = osc.failure("余额支付失败");
                    }
                }else {
                    log.info("余额不足！！！");
                    results = osc.failure("余额不足");
                }
                return results;
            }else if(payType!=null&&payType.equals("微信")){
                results = userWXPay(map);
                return results;
            }else {
                results = osc.failure("请选择支付类型！！！");
                return results;
            }
        }
        return null;
    }


    public String userWXPay(Map<String,String> map){
        //返回结果
        String results="";
        Map resultMap=new HashMap();
        String openid = map.get("openId");
        String name = map.get("name");
        int total_fee = Integer.parseInt(map.get("totalFee"));

        log.debug(openid);
        UserWxPayMyConfig config = null;
        WXPay wxpay =null;
        try {
            config = new UserWxPayMyConfig();
            wxpay= new WXPay(config);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //生成的随机字符串
        String nonce_str = WXPayUtil.generateNonceStr();
        //获取客户端的ip地址
        //获取本机的ip地址
        InetAddress addr = null;
        try {
            addr = InetAddress.getLocalHost();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        String spbill_create_ip = addr.getHostAddress();
        //支付金额，需要转成字符串类型，否则后面的签名会失败
        //int  total_fee=1;
        //商品描述
        String body = "大件支付服务";
        //商户订单号
        //String out_trade_no = getOrderIdByTime();
        String out_trade_no= WXPayUtil.generateNonceStr();
        //统一下单接口参数
        HashMap<String, String> data = new HashMap<String, String>();
        data.put("appid", "wx51d55df222d9901e");    //商户端小程序支付
        data.put("mch_id", "1550181801");
        data.put("nonce_str", nonce_str);
        data.put("body", body);
        data.put("out_trade_no",out_trade_no);
        data.put("total_fee", String.valueOf(total_fee));
        data.put("spbill_create_ip", spbill_create_ip);
        data.put("device_info",map.get("orderId"));
        data.put("notify_url", "https://www.dhnep.cn:443/wxshop/user/userNotify");
        data.put("trade_type","JSAPI");
        data.put("openid", openid);
        try {
            Map<String, String> rMap = wxpay.unifiedOrder(data);
            System.out.println("统一下单接口返回: " + rMap);
            //生成业务充值记录订单
            recharge recharge = new recharge();
            recharge.setOpenId(openid);
            recharge.setName(name);
            recharge.setRechargeTime(new Date());
            recharge.setRechargeSum(Double.valueOf(total_fee)/100);
            recharge.setRechargeNumber(out_trade_no);
            recharge.setPayNumber(rMap.get("prepay_id"));
            recharge.setPayType("微信支付");
            recharge.setPayState("未支付");
            recharge.setBillState("未入账");
            orderService.addRecharge(recharge);
            String return_code = (String) rMap.get("return_code");
            String result_code = (String) rMap.get("result_code");
            String nonceStr = WXPayUtil.generateNonceStr();
            resultMap.put("nonceStr", nonceStr);
            Long timeStamp = System.currentTimeMillis() / 1000;
            if ("SUCCESS".equals(return_code) && return_code.equals(result_code)) {
                String prepayid = rMap.get("prepay_id");
                resultMap.put("package", "prepay_id="+prepayid);
                resultMap.put("signType", "MD5");
                //这边要将返回的时间戳转化成字符串，不然小程序端调用wx.requestPayment方法会报签名错误
                resultMap.put("timeStamp", timeStamp + "");
                //再次签名，这个签名用于小程序端调用wx.requesetPayment方法
                resultMap.put("appId","wx51d55df222d9901e");
                log.debug(resultMap.toString());
                String sign = WXPayUtil.generateSignature(resultMap, "0B2DC615EA4F78BC4B216AEA1A6DA63B");
                resultMap.put("paySign", sign);
                log.debug("生成的签名paySign : "+ sign);
                results = osc.resultSuccess("yes",resultMap);
                return results;
            }else{
                log.debug("生成签名失败！！！");
                results = osc.failure("生成签名失败！！！");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return results;
    }

    /**
     *微信支付回调
     */
    @RequestMapping("/userNotify")
    public String notify(HttpServletRequest request) {
        log.info("======================开始处理微信小程序发送的异步通知==========================");

        //1 获取微信支付异步回调结果
        String xmlResult = WXPayUtil.getPostStr(request);

        Map<String, String> resultMap = null;
        try {
            //将结果转成map
            resultMap = WXPayUtil.xmlToMap(xmlResult);
        } catch (Exception e1) {
            e1.printStackTrace();
        }

        //订单号
        String orderNo = resultMap.get("out_trade_no");
        String orderId = resultMap.get("device_info");
        String total_fee = resultMap.get("total_fee");
        Double money = Double.parseDouble(total_fee);
        log.info("订单号：------------------"+orderNo+"结束----------");
        log.info("订单Id：------------------"+orderId+"结束----------");
        log.info("订单金额：------------------"+money+"结束----------");
        String result_code = resultMap.get("result_code");
        //回调返回的加密签名 保存下来 下面会进行对比
        String sign = resultMap.get("sign");
        //去掉sign和利用微信回调回来的信息重新加密
        resultMap.remove("sign");
        String sign1="";
        try {
            //重新加密 获取加密的签名
            sign1=WXPayUtil.generateSignature(resultMap, "0B2DC615EA4F78BC4B216AEA1A6DA63B"); //签名
        }catch (Exception e){

        }
        String resultCode;
        String resultMsg;
        //对比微信回调的加密与重新加密是否一致  一致即为通过 不一致说明呗改动过 加密不通过
        log.info("==============================================开始对比加密++++++++++++++++++++++++++++++++++++++");
        if (sign.equals(sign1)) { //验签通过
            log.info("==============================================验签通过++++++++++++++++++++++++++++++++++++++");
            log.info(result_code);
            if (result_code.equals("SUCCESS")) {//业务结果为SUCCESS
                /**
                 * 这里写你要处理的逻辑
                 */
                //修改订单状态
                recharge recharge = new recharge();
                recharge.setPayState("已支付");
                recharge.setBillState("已入账");
                recharge.setBillTime(new Date());
                recharge.setRechargeNumber(orderNo);
                boolean updRecharge = recharge(recharge);
                boolean updOrder = order(orderId,money);
                boolean updOrderItem = orderItem(orderId);
                resultCode = "SUCCESS";
                resultMsg = "成功";
            }else{// 业务结果为FALL
                resultCode = "FAIL";
                resultMsg = "业务结果为FAIL";
            }
        }else {
            resultCode = "FAIL";
            resultMsg = "验签未通过";
        }

        Map<String, String> returnMap = new HashMap<>();
        returnMap.put("return_code", resultCode);
        returnMap.put("return_msg", resultMsg);
        try {
            String s = WXPayUtil.mapToXml(returnMap);
            return s;
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }


    public boolean recharge(recharge recharge){
        //获取记录信息
        rechargeExample rEx = new rechargeExample();
        rechargeExample.Criteria criteria = rEx.createCriteria();
        criteria.andRechargeNumberEqualTo(recharge.getRechargeNumber());
        List<cn.itcast.pojo.recharge> recharges = rechargeMapper.selectByExample(rEx);
        if(recharges.isEmpty()){
            return false;
        }else {
            boolean flag = false;
            //修改记录状态
            recharge recharge1 = recharges.get(0);
            recharge1.setBillState(recharge.getBillState());
            recharge1.setPayState(recharge.getPayState());
            int i = rechargeMapper.updateByPrimaryKeySelective(recharge1);
            if(i!=0&&i>0) flag = true;
            else flag = false;
            return flag;
        }
    }

    public boolean order(String orderId,Double total_fee){
        orderExample rEx = new orderExample();
        orderExample.Criteria criteria = rEx.createCriteria();
        criteria.andIdEqualTo(Integer.parseInt(orderId));
        List<cn.itcast.pojo.order> orders = orderMapper.selectByExample(rEx);
        if(orders.isEmpty()){
            return false;
        }else {
            boolean flag = false;
            order order = orders.get(0);
            order.setPayOrderMoney(total_fee);
            order.setOrderState("已完成");
            int upd = orderMapper.updateByPrimaryKeySelective(order);
            boolean money = commission(orderId,total_fee,order.getHorsemanAccount());
            if(upd!=0||upd>0 && money==true) flag = true;
            else flag = false;
            return flag;
        }
    }

    public boolean orderItem(String orderId){
        orderItemExample rEx = new orderItemExample();
        orderItemExample.Criteria criteria = rEx.createCriteria();
        criteria.andOrderIdEqualTo(Integer.parseInt(orderId));
        List<cn.itcast.pojo.orderItem> orderItems = orderItemMapper.selectByExample(rEx);
        if(orderItems.isEmpty()){
            return false;
        }else {
            ArrayList<Integer> itemId = new ArrayList<>();
            for (int i = 0;i<orderItems.size();i++){
                itemId.add(orderItems.get(i).getId());
            }
            for (Integer itemID:itemId){
                orderItem orderItem = orderItemMapper.selectByPrimaryKey(itemID);
                orderItem.setStatus("已打包");
                orderItemMapper.updateByPrimaryKeySelective(orderItem);
            }
            return true;
        }
    }


    public boolean commission(String orderId,Double total_fee,String horseman){
        List<orderItem> orderItemsList = orderItemMapper.findOrderId(Integer.parseInt(orderId));
        List<classsify> classsifyList = classsifyMapper.findName(orderItemsList.get(0).getProductType());
        commissionExample cEx = new commissionExample();
        commissionExample.Criteria criteria = cEx.createCriteria();
        criteria.andCidEqualTo(Long.valueOf(classsifyList.get(0).getFid()));
        List<commission> commissions = commissionMapper.selectByExample(cEx);
        accountExample aEx = new accountExample();
        accountExample.Criteria criteria1 = aEx.createCriteria();
        criteria1.andOpenIdEqualTo(horseman);
        List<account> accountList = accountMapper.selectByExample(aEx);
        if(accountList.isEmpty()){
            return false;
        }else{
            boolean flag = false;
            Double money = total_fee * Double.valueOf(commissions.get(0).getCommission())/100;  //扣取提成
            Double horsemanMoney = DoubleUtils.sub(total_fee,money);   //骑手得到的金额
            Double finallyMoney = DoubleUtils.add(accountList.get(0).getAccountMoneyBalance(),horsemanMoney);
            account account = accountList.get(0);
            account.setAccountMoneyBalance(finallyMoney);
            int i = accountMapper.updateByPrimaryKeySelective(account);
            if(i>0)flag = true;
            else flag = false;
            return flag;
        }
    }



    /**
     *
     * @Description:
     * 用户生成商家订单
     * @auther: 欧阳辉
     * @date: 8:12 2020/3/17
     * @param: [request]
     * @return: java.lang.String
     *
     */
    @PostMapping("merchantaddOrder")
    public String merchantaddOrder(@RequestBody Map<String,String> map) {
        //返回结果
        String results="";
        order order = new order();
        log.debug("添加订单开始");
        order.setOrderState("进行中");
        String orderNumber = getOrderIdByTime();
        order.setOrderNumber(orderNumber);
        order.setOrderVisitTime(map.get("visitTime"));
        order.setOrderTime(new Date());
        order.setLat(map.get("lat"));
        order.setLon(map.get("lat"));
        order.setLat(map.get("addressLat"));
        order.setLon(map.get("addressLon"));
        order.setUserName(map.get("userName"));
        order.setUserArea(map.get("userarea"));
        order.setCounty(map.get("county"));
        order.setUserPhone(map.get("userPhone"));
        order.setOrderExplain(map.get("explain"));
        order.setPayProductType(map.get("productType"));
        order.setPayForecastWeight(map.get("forecastWeight"));
        order.setOpenId(map.get("openId"));
        order.setMerchantopenid(map.get("merchantopenid"));
        order.setOrderform("2");
        //生成订单，推送消息给管理员
        boolean isadd = orderService.merchantaddOrder(order,map.get("productId"));
        if(isadd) {
            Double lat; //纬度
            Double lon; //经度
            if (Strings.isBlank(map.get("lat"))||Strings.isBlank(map.get("lon"))||"0".equals(map.get("lon"))||"0".equals(map.get("lat"))){
                Map<String, Double> userarea = orderServiceimpl.getLngAndLat(map.get("userarea"));
                lat=userarea.get("lat");
                lon=userarea.get("lng");
            }else {
                lat=Double.parseDouble(map.get("lat"));
                lon=Double.parseDouble(map.get("lon"));
            }
            Map<String,Double> latAndLon = new HashMap<>();
            latAndLon.put("userLat",lat);
            latAndLon.put("userLon",lon);
            user user = userMapper.selectFindOneUser(map.get("openId"));
        log.debug("上传成功");
            results = osc.resultSuccess("yes",orderNumber);
        }else {
            results = osc.failure("no");
            log.debug("上传失败");
        }

        return results;
    }


}